
#include "communicatUart1Rx.h"
#include "dma.h"
#include "baseData.h"
#include "diode.h"
#include "led.h"

static uint16_t rxUart1Index = 0;
static uint16_t txUart1Index = 0; 


void uart1RecieveUpdate(void)
{
    txUart1Index = getUart1RemainRecvBuf();
    if(rxUart1Index != txUart1Index)
    {
        int16_t len = txUart1Index - rxUart1Index;
        if (len < 0)
        {
            len += 256;
        }
        uint16_t i = 0;
        while (i < len)
        {
            uint16_t index = rxUart1Index + i;
            i++;
            if (index > 255)
            {
                index -= 256;
            }
            uart1RecieveHandle(g_uart1rx[index]);
        }
        rxUart1Index = txUart1Index;
    }
}
/***
*一帧数据一共收到0xfd+0xfd+37*6+check=2+222+1=225个字节
*
*/
void uart1RecieveHandle(uint8_t data) 
{
    static uint8_t status;	
    static uint8_t cksum;		
    static uint8_t cmd;	 
    static uint8_t pack;	 
	
    static uint8_t bufIndex;  	
    static uint8_t buf[222];
    switch (status)
	{	
		case 0:
			status = (data == 0xFD) ? 1 : 0;
			break;
		case 1:
			status = (data == 0xFD) ? 2 : 0;
			break;
		case 2:
			pack= data;
			cksum = data;
			status=3;
			break;
		case 3: 
			cmd=data;
			bufIndex = 0;
			cksum += data;
			status=4;
			break;
		case 4: 
			buf[bufIndex] = data;
			bufIndex++;
			cksum += data;
			if (bufIndex == 220)//去掉包头2个字节，再减去前面收到的两个字节
			{
				status = 5; 
			}
			break;
		case 5:
			if(cksum == data) /*所有校验正确*/
			{
				uart1Recieved(pack,cmd,buf);
			}
			status = 0;
			cksum=0;
			break;
	 
		default:
			break;
    }
}

/*
*
**/
void uart1Recieved(uint8_t pack,uint8_t cmd,uint8_t *data)
{
	static uint8_t packtmp=0;
	
	if(packtmp!=pack)
	{
		packtmp=pack;
		switch (cmd)
		{
			case 0:
			break;
			case 1:
				led_set(data[0],data[1],data[2]);
			break;
			case 2:
				 
			break; 
			default:
			break;
		}
	}
	
	for(uint8_t i=0;i<216;i++)//数据+1个check
	{
		From_to.Usart1_to_Usart3[i]=data[i+4];
	}
}



